package com.wanyangproject.widget.popupwindow;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.wanyangproject.R;
import com.wanyangproject.net.util.AppSession;


public abstract class BasePopupWindow extends PopupWindow {

    protected Context mContext;
    protected String mValue;
    private View rootView;
    protected OnChooseDataListener listener;
    protected AppSession mSession;

    public BasePopupWindow(Context context) {
        mContext = context;
        initPopupWindow();
    }

    public BasePopupWindow(Context context, String value) {
        mContext = context;
        mValue = value;
        initPopupWindow();
    }

    private void initPopupWindow() {
        /**加载视图*/
        rootView = initView();
        mSession = AppSession.getInstance(mContext);
        /**设置弹窗以外触摸事件*/
        this.setOutsideTouchable(true);
        rootView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = rootView.findViewById(R.id.pop_outer).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        myDismiss();
                    }
                }
                return true;
            }
        });

        /**设置视图*/
        this.setContentView(rootView);
        /**设置弹出窗体的宽和高*/
        this.setHeight(RelativeLayout.LayoutParams.MATCH_PARENT);
        this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        /**设置弹出窗体可点击*/
        this.setFocusable(true);
        /**设置弹出窗体的背景为半透明*/
        this.setBackgroundDrawable(new ColorDrawable(0x55000000));
        /**设置弹出窗体显示时的动画，从底部向上弹出*/
        this.setAnimationStyle(R.style.popup_window_bottom_animation);

        /**事务处理*/
        init();
    }

    private View initView() {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(layoutResId(), null);
        return view;
    }

    public <T> T findViewById(int id) {
        T view = (T) rootView.findViewById(id);
        return view;
    }

    public void myDismiss() {
        dismiss();
    }

    public void setOnChooseDataListener(OnChooseDataListener listener) {
        this.listener = listener;
    }

    public abstract int layoutResId();
    public abstract void init();
}